import Vue from 'vue'
import VueRouter from 'vue-router'
import login from '@/views/login'
import home from '@/views/home'
import welcome from '@/views/welcome'
import users from '@/views/user'
import rights from '@/views/rights'
import roles from '@/views/roles'
import params from '@/views/params'

Vue.use(VueRouter)

const routes = [
  { path: '/', redirect: '/login' },
  { path: '/login', component: login },
  {
    path: '/home',
    component: home,
    redirect: '/welcome',
    children: [
      { path: '/welcome', component: welcome },
      { path: '/users', component: users },
      { path: '/rights', component: rights },
      { path: '/roles', component: roles },
      { path: '/params', component: params }
    ]
  }
]

const router = new VueRouter({
  routes
})

// 导航守卫，判断是否有 token
router.beforeEach((to, from, next) => {
  if (to.path === '/login') return next()
  const tokenStr = window.sessionStorage.getItem('token')
  if (tokenStr) {
    next()
  } else {
    next('/login')
  }
})

export default router
